import GRDB

// MARK: - 数据库管理器
final class DatabaseRecordManager {
    static let shared = DatabaseRecordManager()
    var dbQueue: DatabaseQueue
    
    private init() {
        do {
            let dbURL = try FileManager.default
                .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
                .appendingPathComponent("record.db")
            
            dbQueue = try DatabaseQueue(path: dbURL.path)
            try migrateDatabase()
        } catch {
            fatalError("Database initialization failed: \(error)")
        }
    }
}

// MARK: - 版本管理
extension DatabaseRecordManager {
    /// 数据库版本枚举（集中管理）
    private enum Version: Int {
        case migration_1 = 1
    }
    /// 迁移操作结构体
    private struct Migration {
        let version: Version
        let migrate: (Database) throws -> Void
    }
    
    /// 所有迁移操作（按版本顺序排列）
    private var migrations: [Migration] {
        [
            Migration(version: .migration_1) { db in
                // 自定义api
                if try! !db.tableExists("aiCustom") {
                    try db.create(table: "aiCustom") { t in
                        t.column("objectId", .text).primaryKey()
                        t.column("name", .text)
                        t.column("host", .text)
                        t.column("token", .text)
                        t.column("model", .text)
                        t.column("active", .integer)
                        t.column("temperature", .double)
                        t.column("url", .text)
                        t.column("top_p",  .double)
                        t.column("sort",  .integer)
                    }
                }
                // 自定义api错误
                if try! !db.tableExists("aiCustomError") {
                    try db.create(table: "aiCustomError") { t in
                        t.column("objectId", .text).primaryKey()
                        t.column("name", .text)
                        t.column("id", .text)
                        t.column("host", .text)
                        t.column("token", .text)
                        t.column("model", .text)
                        t.column("time", .integer).notNull().defaults(to: 0)
                        t.column("content", .text)
                    }
                }
            },
        ].sorted { $0.version.rawValue < $1.version.rawValue } // 确保升序排列
    }
    
    /// 执行数据库迁移
    private func migrateDatabase() throws {
        let currentVersion = try getCurrentVersion()
        showLog("记录数据库版本: \(currentVersion)")
        
        // 筛选需要执行的迁移
        let pendingMigrations = migrations.filter {
            $0.version.rawValue > currentVersion
        }
        
        guard !pendingMigrations.isEmpty else {
            showLog("Database is up to date")
            return
        }
        
        showLog("Pending migrations: \(pendingMigrations.count)")
        
        // 执行迁移队列
        for migration in pendingMigrations {
            try dbQueue.write { db in
                do {
                    showLog("Migrating to version \(migration.version.rawValue)...")
                    try migration.migrate(db)
                    try setVersion(db: db, version: migration.version.rawValue)
                    showLog("Migration to version \(migration.version.rawValue) succeeded")
                } catch {
                    showLog("Migration to version \(migration.version.rawValue) failed: \(error)")
                    throw error
                }
            }
        }
        
        showLog("Final database version: \(try getCurrentVersion())")
    }
}

// MARK: - 版本控制
extension DatabaseRecordManager {
    /// 获取当前数据库版本
    private func getCurrentVersion() throws -> Int {
        try dbQueue.read { db in
            try Int.fetchOne(db, sql: "PRAGMA user_version") ?? 0
        }
    }
    
    /// 设置数据库版本
    private func setVersion(db: Database, version: Int) throws {
        try db.execute(sql: "PRAGMA user_version = \(version)")
    }
}

// MARK: - 使用示例
/*
 // 在AppDelegate中初始化
 _ = DatabaseFolderManager.shared
 
 // 检查当前版本
 do {
 let version = try DatabaseManager.shared.getCurrentVersion()
 showLog("Current DB version: \(version)")
 } catch {
 showLog("Version check failed: \(error)")
 }
 */
